package com.mapull.simple;

import java.util.Arrays;

/**
 * 快速排序-双边循环
 *
 * @author mapull
 * @date 2022-06-05
 */
public class QuickDouble {

    public static void main(String[] args) {
        int[] nums = {5, 9, 7, 4, 1, 8, 3, 2, 6};
        System.out.println("排序前 " + Arrays.toString(nums));
        quickSort(nums, 0, nums.length - 1);
        System.out.println("排序后 " + Arrays.toString(nums));
    }

    private static void quickSort(int[] nums, int left, int right){
        if(left >= right){
            return;
        }
        int cur = partition(nums, left, right);
        quickSort(nums, left, cur -1);
        quickSort(nums, cur + 1, right);
    }

    private static int partition(int[] nums, int left, int right) {
        // 基准点选择最左边的元素
        int pv = nums[left];
        int i = left;
        int j = right;
        while(i < j){
            // j 从右边开始找比基准点的小的元素
            while(i < j && nums[j] > pv){
                j--;
            }
            // i 从左边开始找比基准点大的元素
            while (i < j && nums[i] <= pv){
                i++;
            }
            swap(nums, i, j);
        }
        swap(nums, left, i);
        return i;
    }

    private static void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
